package com.google.donutrush;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Entities.User;
import Services.Mailman;
import Services.SignedRequestDecoder;
import Services.UserService;
import Services.UserServiceDBimpl;

import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

public class FacebookRegister extends HttpServlet {
	
	public void Get(HttpServletRequest request, HttpServletResponse response)
	throws IOException {
		doPost(request, response);
	
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException {
		
		UserService us = UserServiceDBimpl.getInstance();
		boolean isRegSuccesfull = false;
		
		String input = (String)request.getParameter("signed_request").toString();
		
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap = SignedRequestDecoder.parse_signed_request(input, "34aa58ecb2e063c650eadc5b9983a2d7",response);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			//e1.printStackTrace();
			response.setContentType("text/plain");
			PrintWriter writer = null;
			try {
				writer = response.getWriter();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			writer.println(e1);
			writer.close();
			}

			
		//Prepare the json object we create from the request body
		JSONObject jsonObject = null;
		jsonObject = (JSONObject)jsonMap.get("registration");
		
		//getting all filled params in the registration form of the json object
		String name = "";
		String email = "";
		String password = "";
		String fbID = "invalid";
		
		try {
			name = (String) jsonObject.get("name");
			email = (String) jsonObject.get("email");
			password = (String) jsonObject.get("password");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		fbID = (String)jsonMap.get("user_id");
		User newuser;
		if(fbID !=null){
			newuser = new User(name, email, password, fbID, true);
		}
		else{
			newuser = new User(name, email, password, "invalid", false);
		}
		//first register new user to user DB, maybe with errors
		if (!(newuser.getName().equals("")) && !(newuser.getEmail().equals("")) && !(newuser.getPassword().equals(""))){
			isRegSuccesfull = us.registerUser(newuser);
		}
		
		if(!isRegSuccesfull){
			ServletContext context = getServletContext();
			context.setAttribute("error", "Register failed, either user name or e-mail are already taken!");
			RequestDispatcher rd = request.getRequestDispatcher("Error.do");
			try {
				rd.forward(request, response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else{
		
		//send ver email
		if (!newuser.isFacebookUser()){
			Mailman.sendVerMail("zzzoshri@gmail.com", newuser.getEmail(), newuser.getName(), newuser.getEmail(), newuser.getPassword());
			}
		}
		
		
		if(isRegSuccesfull){
			response.sendRedirect(response.encodeRedirectURL("http://apps.facebook.com/donut-rush/"));
		}
		
		
	
		
		//from here is just the way to sent the json back to the client
		
		
		response.setContentType("text/plain");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		writer.println(jsonMap);
		writer.close();
	
		
	}

}
